package com.nanyiba.qrcode.base.api;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanyiba.qrcode.websocket.WebSocketSessionOpr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.WebSocketSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 熊腾强
 * @Date 2021/7/30 3:23 下午
 * @Description
 */
@CrossOrigin
@RestController
@RequestMapping("/qrCode")
public class QrCodeApi {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    /**
     * 密钥
     */
    byte[] key = "nanyiba.com".getBytes();

    /**
     * 同意授权
     * @param platform
     * @param token
     * @return
     */
    @GetMapping("/agree")
    public Map<String, Object> agree(String platform, String token) throws JsonProcessingException {
        Map<String, Object> res = new HashMap<>(2);
        Map<String, Object> authRes = new HashMap<>(2);
        boolean verify = false;
        try {
            verify = JWT.of(token).setKey(key).validate(0);
        }catch (JWTException jwtException){
            res.put("success", false);
            res.put("msg", "token被非法篡改");
            authRes.put("success", false);
            authRes.put("msg", "授权失败,token被非法篡改");
        }
        if(verify) {
            res.put("success", true);
            res.put("msg", "成功");
            res.put("url", "http://nchfly.cn");
            authRes.put("success", true);
            authRes.put("msg", "授权成功");
            authRes.put("url", "http://nchfly.cn");
        }else {
            if(!res.containsKey("success")){
                res.put("success", false);
                res.put("msg", "token已过期");
                authRes.put("success", false);
                authRes.put("msg", "授权失败,token已过期");
            }
        }

        //告诉扫码二维码页面授权结果,授权通过了,则跳转到业务主页面
        WebSocketSession webSocketSession = WebSocketSessionOpr.get(token);
        if (webSocketSession != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            String msg = objectMapper.writeValueAsString(authRes);
            simpMessagingTemplate.convertAndSendToUser(token, "/queue/authRes", msg);
        }

        return res;
    }

    /**
     * 生成jwt令牌
     * @param mobile
     * @return
     */
    @Cacheable(value="jwt", key="#mobile")
    @GetMapping("/generateJwt")
    public Map<String, Object> generateJwt(String mobile){
        long expires = System.currentTimeMillis() + 1000 * 60 * 2;
        String token = JWT.create()
                .setPayload("mobile", mobile)
                .setKey(key)
                //过期时间2分钟
                .setExpiresAt(new Date(expires))
                .sign();
        Map<String, Object> res = new HashMap<>(2);
        res.put("success", true);
        res.put("token", token);
        return res;
    }

    /**
     * 生成二维码
     * @return
     */
    @GetMapping("/generateQrCode")
    public Map<String, Object> generateQrCode() {
        //登陆授权页面
        String dlAuthorUrl = "http://210.22.22.150:5306/nanyiba-qrCode-show/authPage.html";
        String fileName = IdUtil.simpleUUID();
        String path = System.getProperty("user.dir") + "/qrCode/" + fileName + ".jpg";
        QrCodeUtil.generate(dlAuthorUrl, 300, 300, FileUtil.file(path));
        Map<String, Object> res = new HashMap<>(2);
        res.put("success", true);
        res.put("qrCodeUrl", "http://210.22.22.150:4164/qrCode/"+ fileName + ".jpg");
        return res;
    }

    /**
     * 清除缓存
     * @param mobile
     * @return
     */
    @CacheEvict(value="jwt", key="#mobile")
    @GetMapping("/delete")
    public Map<String, Object> delete(String mobile) {
        Map<String, Object> res = new HashMap<>(2);
        res.put("success", true);
        res.put("msg", "清除"+ mobile + "token缓存");
        return res;
    }

    @CacheEvict(value="jwt", allEntries = true)
    public Map<String, Object> deleteAll() {
        Map<String, Object> res = new HashMap<>(2);
        res.put("success", true);
        res.put("msg", "清除所有缓存");
        return res;
    }
}
